package pl.edu.utp.ga.selections;

import pl.edu.utp.ga.Individual;
import pl.edu.utp.ga.Parents;
import pl.edu.utp.ga.Population;

public class RouletteWheelSelection extends BaseSelection{
	
	private int sum;
	private int populationSize;
	
	public RouletteWheelSelection(){
		super();
	}
	
	@Override
	public void setPopulation(Population population) {
		this.population = population;
		populationSize = population.getSize(); 
		sum = summation(populationSize);
	}

	@Override
	public Parents selectParents() {
		Individual firstParent = population.getIndividual(chooseParent());
		Individual secondParent = population.getIndividual(chooseParent());
		return new Parents(firstParent,secondParent);
	}
	
	private int summation(int populationSize){
		int s = 0;
		for(int i=1; i<=populationSize; i++){
			s += i;
		}
		return s;
	}
	
	private int chooseParent(){
		int index = populationSize-1;
		int s = 0;
		int checkPoint = random.nextInt(sum);
		for(int i=1; i<=populationSize; i++, index--){
			s += i;
			if(s >=checkPoint){
				break;
			}
		}
		return index;
	}

}
